package com.mall.url;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.entity.Permission;
import com.mall.user.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
@Component("urlFilterInvocationSecurityMetadataSource")
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 获取当前请求url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        String url = requestUrl;
        if (requestUrl.indexOf('?') != -1) {
            url = requestUrl.substring(0, requestUrl.indexOf('?'));
        }

//        //获取到该url所需要的权限
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Permission::getPath,url);
        Permission permission = permissionMapper.selectOne(queryWrapper);

        if (permission != null) {
            String permissionValue = permission.getPermissionValue();
            return SecurityConfig.createList(permissionValue);
        }
        // 如果数据中没有找到相应url资源则为非法访问，要求用户登录再进行操作
        return SecurityConfig.createList("no");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
